package route

import (
	"fmt"
	"more_ssh/conf"
	"more_ssh/middleware"
	"more_ssh/sql"
	"net/http"

	"github.com/gin-gonic/gin"
)

func login(c *gin.Context) {
	user := make(map[string]string)
	c.BindJSON(&user)

	//判断账号密码是否都携带
	if user["password"] == "" || user["username"] == "" {
		fmt.Println("参数不完整:suer:" + user["username"] + " password: " + user["password"])
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "参数不完整",
		})
		return
	}

	// 校验账号密码是否正确
	// userInfo, err := sql.QueryUser(user["username"], conf.DB)
	// comma, ok := user["password"].(string)
	user1 := &sql.User{}
	line := conf.DB.Where("user=?", user["username"]).First(user1).RowsAffected

	// if !ok {
	// 	fmt.Println("提交有问题")
	// }
	// // fmt.Println(comma, userInfo)
	// if comma == userInfo.User {
	// 	fmt.Println("验证通过")
	// }

	if line == 0 {
		fmt.Println(user["username"] + "用户不存在")
		// fmt.Println("登录失败", err)
		c.JSON(http.StatusAccepted, gin.H{
			"msg": user["username"] + "用户不存在",
		})
		return
	}

	if user1.Password != user["password"] {
		fmt.Println("密码不正确！")
		c.JSON(http.StatusAccepted, gin.H{
			"msg": "密码不正确！",
		})
		return
	}

	// userInfo.Password == user["password"]
	// fmt.Printf("\ndb---------------:%#v  user--------------:%#v\n", db, user["username"])
	token, _ := middleware.CreateToken(user1.ID)
	c.JSON(http.StatusOK, gin.H{
		"msg":           "登录成功",
		"Authorization": token,
	})
}
